from django.db import models
from django.contrib.auth.models import User
import uuid,json,time,random

class UserGroup(models.Model):
    title = models.CharField(max_length=32)

class UserInfo(models.Model):
    # user_type_choices = (
    #     (1,'普通用户'),
    #     (2,'VIP'),
    #     (3,'SVIP'),
    # )
    # user_type = models.IntegerField(choices=user_type_choices)

    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    weixin_openid = models.CharField(max_length=128, unique=True, null=True, help_text='微信openid')
    email = models.CharField(max_length=32,null=True)
    mobile = models.CharField(max_length=32,null=True)
    mg_state = models.BooleanField(default=False)
    create_time = models.DateTimeField('创建时间',auto_now_add=True)
    roles = models.ManyToManyField("Role",blank=True)
    # roles = models.OneToOneField("Role", on_delete=models.CASCADE)

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="用户")
    nickname = models.CharField(max_length=128, null=True, help_text='昵称')
    avatar = models.CharField(max_length=512, null=True, help_text='头像')
    sex = models.IntegerField(default=0, help_text='性别')
    remaining_sum = models.FloatField(default=0.0, help_text='余额')
    accumulate = models.IntegerField(default=0, help_text='积分')
    weixin_openid = models.CharField(max_length=128, unique=True, null=True, help_text='微信openid')
    is_delete = models.BooleanField(default=False)
    remark = models.CharField(max_length=128, null=True, help_text='备注信息')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['-id']

    def customer_save(self, nickname, avatar, sex, weixin_openid):
        if weixin_openid:
            user = User()
            user.username = uuid.uuid4()
            user.set_password(str(uuid.uuid4()))
            user.is_staff = False
            user.is_superuser = False
            user.save()

            self.user = user
            self.nickname = nickname
            self.sex = sex
            self.avatar = avatar
            self.weixin_openid = weixin_openid

            self.save()
        return self

    def customer_update(self, nickname, avatar, sex):
        if nickname:
            self.nickname = nickname
            self.sex = sex
            self.avatar = avatar

            self.save()
        return self

    # def __str__(self):
    #     return self.username


class UserToken(models.Model):
    user = models.OneToOneField(to='UserInfo',on_delete=models.CASCADE)
    token = models.CharField(max_length=64)


class Role(models.Model):
    roleName = models.CharField(max_length=32)
    roleDesc = models.CharField(max_length=64,null=True,blank=True)
    permissions = models.ManyToManyField('Permission',blank=True)

    def __str__(self):
        return self.roleName

class Menu(models.Model):
    menuName = models.CharField(max_length=32,verbose_name='一级菜单名称')
    icon = models.CharField(verbose_name='图标', max_length=32, null=True, blank=True)

    def __str__(self):
        return self.menuName

class Permission(models.Model):
    authName = models.CharField(max_length=32,verbose_name='权限说明')
    url = models.CharField(max_length=128,verbose_name='含正则的url')
    # is_menu = models.BooleanField(verbose_name='是否可以做菜单',default=False)
    # icon = models.CharField(verbose_name='图标',max_length=32,null=True,blank=True)
    menu = models.ForeignKey('Menu',null=True,blank=True,
                             help_text='null表示不是菜单；非null表示是二级菜单',on_delete=models.CASCADE)
    pid = models.ForeignKey('Permission',related_name='parents',on_delete=models.CASCADE,null=True,blank=True)
    level = models.CharField(max_length=16,verbose_name='权限层级')

    def __str__(self):
        return self.authName

class Goods(models.Model):
    goods_state_choices = (
        (0,'未通过'),
        (2,'审核中'),
        (3,'已审核'),
    )
    goods_id = models.AutoField(primary_key=True)
    goods_state = models.IntegerField(choices=goods_state_choices,default=3)
    is_onsale = models.BooleanField(default=True, help_text='是否上架')
    goods_name = models.CharField(max_length=256, help_text='商品名称')
    # goods_cat = models.ForeignKey('Categories',on_delete=models.CASCADE)
    goods_cat = models.CharField(max_length=32)
    goods_number = models.IntegerField(default=0, help_text='数量')
    sale_num = models.IntegerField(default=0,null=True, help_text='销售数量')
    read_num = models.IntegerField(default=0, help_text='浏览量')
    # goods_sn = models.CharField(max_length=64, help_text='商品编号')
    # category = models.ForeignKey(Category, on_delete=models.CASCADE, help_text='商品分类')
    # category_list = models.CharField(max_length=128, null=True,  help_text='分类列表')
    # goods_image = models.CharField(max_length=512, null=True, help_text='商品主图')
    # gallery = models.CharField(max_length=5000, null=True, help_text='轮播图')
    # is_onsale = models.BooleanField(default=True, help_text='是否上架')
    # is_recommend = models.BooleanField(default=False, help_text='是否推荐')
    is_promote = models.BooleanField(default=False, help_text='是否是热销品')
    hot_number = models.IntegerField(default=0, help_text='热销品数量')
    # unit = models.CharField(max_length=12, help_text='单位')
    goods_price = models.FloatField(default=0.0, help_text='价格')
    ori_price = models.FloatField(default=0.0, help_text='原价')
    # number = models.IntegerField(default=0, help_text='库存')
    goods_weight = models.FloatField(default=0.0, help_text='重量')
    goods_introduce = models.TextField(null=True, help_text='详情')
    # ori_price = models.FloatField(default=0.0, help_text='原价')
    # detail = models.TextField(null=True, help_text='详情')
    # order = models.IntegerField(default=0, help_text='排序值')
    # sale_num = models.IntegerField(default=0, help_text='销量')
    # read_num = models.IntegerField(default=0, help_text='浏览量')
    is_delete = models.BooleanField(default=False)
    add_time = models.DateTimeField(auto_now_add=True, null=True,help_text='添加时间')
    upd_time = models.DateTimeField(auto_now_add=True, null=True,help_text='更新时间')
    modify_date = models.DateTimeField(auto_now=True, null=True)
    pics = models.JSONField(null=True,blank=True)
    attrs = models.JSONField(null=True,blank=True)

    def __str__(self):
        return self.goods_name
class GoodsSpecification(models.Model):
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE)
    specification = models.CharField(max_length=256, null=True, help_text='规格名称')
    value = models.CharField(max_length=256, null=True, help_text='商品参数值')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['id']

    def __str__(self):
        return str(self.goods)+' ' +self.specification

    def specification_save(self, goods, specificationDic):
        if goods:
            self.goods = goods
            self.specification = specificationDic['specification']
            self.value = specificationDic['value']
            self.save()
        return self

class GoodsProduct(models.Model):
    goods = models.ManyToManyField(to='Goods')
    specifications = models.CharField(max_length=1024, null=True, help_text='规格列表')
    price = models.FloatField(default=0.0, help_text='价格')
    number = models.IntegerField(default=0, help_text='库存')
    goods_image = models.JSONField(null=True, blank=True,help_text='商品主图')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['id']

    def __str__(self):
        return self.specifications

    def product_save(self, goods, productDic):
        if goods:
            self.goods = goods
            self.specifications = json.dumps(productDic['specifications'])
            self.price = productDic['price']
            self.number = productDic['number']
            self.goods_image = productDic['goods_image']
            self.save()
        return self

class Categories(models.Model):
    cat_id = models.AutoField(primary_key=True)
    cat_name = models.CharField(max_length=256, help_text='分类名称')
    # cat_pid = models.ForeignKey('Categories',related_name='parents',on_delete=models.CASCADE,null=True,blank=True)
    cat_pid = models.IntegerField(default=0)
    cat_level = models.IntegerField(default=3, verbose_name='分类等级')
    image = models.JSONField(null=True, blank=True)
    cat_deleted = models.BooleanField(default=False, help_text='分类是否有效')

    def __str__(self):
        return self.cat_name

class Params(models.Model):
    attr_write_choices = (
        (0,'list'),
        (1,'manual')
    )
    attr_sel_choices = (
        (0,'many'),
        (1,'only')
    )
    attr_id = models.AutoField(primary_key=True)
    cat_id = models.ForeignKey('Categories',on_delete=models.CASCADE)
    attr_name = models.CharField(max_length=32, help_text='分类参数名称')
    attr_sel = models.IntegerField(choices=attr_sel_choices, help_text='分类参数类型')
    attr_write = models.IntegerField(choices=attr_write_choices,null=True,blank=True,
                                     help_text='list表示从列表选择（动态参数），manual表示手工录入（静态属性）')
    attr_vals = models.CharField(max_length=256, help_text='分类参数明细')

    def __str__(self):
        return self.attr_name

class Order(models.Model):
    order_id = models.AutoField(primary_key=True)
    order_number = models.CharField(max_length=32,verbose_name='订单编号')
    order_price = models.CharField(max_length=32)
    pay_status = models.SmallIntegerField(default=0,help_text="是否付款")
    is_send = models.CharField(max_length=16,default='否',help_text="是否发货")
    consignee_addr = models.CharField(max_length=64,help_text="收件地址")
    create_time = models.DateTimeField(auto_now_add=True, null=True,help_text='创建时间')
    update_time = models.DateTimeField(auto_now_add=True, null=True,help_text='更新时间')
    goods = models.ManyToManyField('Goods')

    def __str__(self):
        return self.order_number


class HotSearch(models.Model):
    name = models.CharField(max_length=64, help_text='热搜名称')
    order = models.IntegerField(default=0, help_text='排序值')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['order']

    def search_save(self, request):
        json_data = json.loads(request.body)
        name = json_data['name']
        order = int(json_data['order'])

        if name:
            self.name = name
            self.order = order
            self.save()
        return self

class Ad(models.Model):
    name = models.CharField(max_length=64, help_text='广告名称')
    image = models.JSONField(null=True,blank=True,help_text='广告图地址')
    link = models.CharField(max_length=512, help_text='跳转地址')
    position = models.IntegerField(default=0, help_text='位置，0：首页轮播，1：中间')
    order = models.IntegerField(default=0, help_text='排序值')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return self.name

    def ad_save(self, request):
        json_data = json.loads(request.body)
        name = json_data['name']
        link = json_data['link']
        image = json_data['image']
        position = json_data['position']
        order = int(json_data['order'])

        if name:
            self.name = name
            self.link = link
            self.image = image
            self.position = position
            self.order = order
            self.save()
        return self

class MallModels(models.Model):
    name = models.CharField(max_length=64, help_text='模块名称')
    image = models.JSONField(null=True,blank=True,help_text='模块图标')
    link = models.CharField(max_length=512, help_text='跳转地址')
    type = models.IntegerField(default=0, help_text='类型，0：小程序内部，1：小程序外部')
    order = models.IntegerField(default=0, help_text='排序值')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['order']

    def mallmodels_save(self, request):
        json_data = json.loads(request.body)
        name = json_data['name']
        link = json_data['link']
        image = json_data['image']
        type = json_data['type']
        order = int(json_data['order'])

        if name:
            self.name = name
            self.link = link
            self.image = image
            self.type = type
            self.order = order
            self.save()
        return self

class IAS(models.Model):
    name = models.CharField(max_length=64)
    server = models.CharField(max_length=64)
    path = models.CharField(max_length=64)
    image = models.JSONField(null=True, blank=True)
    ias_cat = models.CharField(max_length=32)
    xxx = models.IntegerField(default=0, help_text='排序值')
    version = models.CharField(max_length=64,help_text='目前版本')

    def __str__(self):
        return self.name

class CarefullyChosen(models.Model):
    name = models.CharField(max_length=64, help_text='精选名称')
    image = models.JSONField(null=True,blank=True)
    goods = models.ManyToManyField('Goods', help_text='精选商品id列表')
    order = models.IntegerField(default=0, help_text='排序值')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['order']

    def carefullychosen_save(self, request):
        json_data = json.loads(request.body)
        name = json_data['name']
        image = json_data['image']
        goods = json_data['goods']
        order = int(json_data['order'])

        if name:
            self.name = name
            self.image = image
            self.goods = json.dumps(goods)
            self.order = order
            self.save()
        return self

class StoreService(models.Model):
    name = models.CharField(max_length=128, help_text='服务名称')
    order = models.IntegerField(default=0, help_text='排序值')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['order']

    def service_save(self, request):
        json_data = json.loads(request.body)
        name = json_data['name']
        order = int(json_data['order'])

        if name:
            self.name = name
            self.order = order
            self.save()
        return self

class FootPoint(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE)
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['-id']

    def footpoint_save(self, customerObj, goodsObj):

        if customerObj:
            self.customer = customerObj
            self.goods = goodsObj
            self.save()
        return self

class Collect(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE)
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['-id']

    def collect_save(self, customerObj, goodsObj):
        if customerObj:
            self.customer = customerObj
            self.goods = goodsObj
            self.save()
        return self

class CustomerAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    name = models.CharField(max_length=64, help_text='姓名')
    phone_number = models.CharField(max_length=16, help_text='手机号码')
    address = models.CharField(max_length=128, help_text='地图选择地址')
    address_detail = models.CharField(max_length=128, null=True, help_text='详细地址')
    longitude = models.CharField(max_length=64, null=True, help_text='经度')
    latitude = models.CharField(max_length=64, null=True, help_text='纬度')
    is_default = models.BooleanField(default=False)
    is_delete = models.BooleanField(default=False)
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['-id']

    def address_save(self, request, user_id):
        json_data = json.loads(request.body)
        name = json_data['name']
        phone_number = json_data['phone_number']
        address = json_data['address']
        address_detail = json_data['address_detail']
        longitude = json_data['longitude']
        latitude = json_data['latitude']
        is_default = json_data['is_default']

        if name:
            self.customer = Customer.objects.get(user_id=user_id)
            self.name = name
            self.phone_number = phone_number
            self.address = address
            self.address_detail = address_detail
            self.longitude = longitude
            self.latitude = latitude
            if is_default:
                try:
                    addressObj = CustomerAddress.objects.get(customer__user_id=user_id, is_delete=False, is_default=True)
                    addressObj.is_default = False
                    addressObj.save()
                    self.is_default = is_default
                except:
                    self.is_default = is_default

            self.save()
        return self

class Cart(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, null=True, on_delete=models.SET_NULL)
    number = models.IntegerField(default=0, help_text='数量')
    specifications = models.CharField(max_length=1024, null=True, help_text='规格列表')
    is_delete = models.BooleanField(default=False, help_text='逻辑删除')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['id']

    def cart_save(self, user_id, goods_id, specifications, number):
        if goods_id:
            customerObj = Customer.objects.get(user_id=user_id)
            goodsObj = Goods.objects.get(goods_id=goods_id)
            self.customer = customerObj
            self.goods = goodsObj
            self.number = number
            self.specifications = json.dumps(specifications)
            self.save()
        return self

class GoodsOrder(models.Model):
    id = models.CharField(max_length=72, primary_key=True, unique=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    address_obj = models.ForeignKey(CustomerAddress, null=True, on_delete=models.SET_NULL)
    contacts_name = models.CharField(max_length=30, null=True, help_text='联系人')
    phone_number = models.CharField(max_length=16, help_text='手机号码')
    address = models.CharField(max_length=256, help_text='地址')
    longitude = models.CharField(max_length=64, null=True, help_text='经度')
    latitude = models.CharField(max_length=64, null=True, help_text='纬度')
    total_price = models.FloatField(default=0.0, help_text='商品价格')
    actual_price = models.FloatField(default=0.0, help_text='实际支付')
    order_remark = models.CharField(max_length=128, null=True, help_text='备注信息')
    #0--提交 1-用户确认  2--支付  3--发货  6--交易成功  7--评价完成  8--申请退款  9--退款完成  10--交易关闭
    status = models.IntegerField(default=0, help_text='订单状态')
    express_sn = models.CharField(max_length=64, null=True, help_text='运单号')
    express_name = models.CharField(max_length=64, null=True, help_text='快递公司')
    express_time = models.DateTimeField(null=True, help_text='发货时间')
    confirm_time = models.DateTimeField(null=True, help_text='确认收货时间')
    is_pay = models.BooleanField(default=False, help_text='是否支付')
    pay_date = models.DateTimeField(null=True, help_text='支付时间')
    is_pay_back = models.BooleanField(default=False, help_text='是否申请退款')
    refund_number = models.FloatField(default=0.0, help_text='退款数额')
    open_id = models.CharField(max_length=128, null=True, help_text='支付者微信openid')
    out_trade_no = models.CharField(max_length=128, null=True, help_text='商户系统订单号')
    nonce_str = models.CharField(max_length=128, null=True, help_text='随机字符串')
    wx_pay_back_mony = models.FloatField(default=0.0, help_text='回调函数返回的金额')
    wx_popularize_mony = models.FloatField(default=0.0, help_text='微信商户平台活动金额，如优惠券')
    is_delete = models.BooleanField(default=False, help_text='逻辑删除')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['-create_date']

    def goodsorder_add(self, user_id):
        if user_id:
            self.id = str(int(time.time())) + str(random.randint(100000, 999999))
            customerObj = Customer.objects.get(user_id=user_id)
            self.customer = customerObj
            self.save()
        return self

class GoodsOrderGoods(models.Model):
    order = models.ForeignKey(GoodsOrder, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=256, help_text='商品名称')
    goods_image = models.CharField(max_length=512, null=True, help_text='商品主图')
    price = models.FloatField(default=0.0, help_text='价格')
    amount = models.IntegerField(default=0, help_text='数量')
    specifications = models.CharField(max_length=1024, null=True, help_text='规格列表')
    is_delete = models.BooleanField(default=False, help_text='逻辑删除')
    create_date = models.DateTimeField(auto_now_add=True, null=True)
    modify_date = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ['id']

    def goods_add(self, order, goodsObj, productObj, amount, specifications):
        if order:
            self.order = order
            self.goods = goodsObj
            self.name = goodsObj.goods_name
            self.goods_image = productObj.goods_image
            self.price = productObj.price
            self.amount = amount
            self.specifications = specifications
            self.save()
        return self